#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right)
    {
    }
};

class Solution 
{
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) 
    {
        if(root == nullptr)
        {
            return new TreeNode(val);
        }
        TreeNode * node = root;
        while(node)
        {
            if(val > node->val)
            {
                if(node->right == nullptr)
                {
                    node->right = new TreeNode(val);
                    break;
                }
                node = node->right;
            }
            else if (val < node->val)
            {
                if(node->left == nullptr)
                {
                    node->left = new TreeNode(val);
                    break;
                }
                node = node->left;
            }
        }
        return root;
    }
};

// 辅助函数：从数组构建二叉搜索树（层序遍历方式，-1表示null）
TreeNode *buildTreeFromArray(vector<int> &arr)
{
    if (arr.empty() || arr[0] == -1) return nullptr;

    TreeNode *root = new TreeNode(arr[0]);
    queue<TreeNode *> q;
    q.push(root);

    int i = 1;
    while (!q.empty() && i < arr.size())
    {
        TreeNode *node = q.front();
        q.pop();

        // 左子节点
        if (i < arr.size() && arr[i] != -1)
        {
            node->left = new TreeNode(arr[i]);
            q.push(node->left);
        }
        i++;

        // 右子节点
        if (i < arr.size() && arr[i] != -1)
        {
            node->right = new TreeNode(arr[i]);
            q.push(node->right);
        }
        i++;
    }

    return root;
}

// 辅助函数：层序遍历打印二叉树
void printTree(TreeNode *root)
{
    if (!root)
    {
        cout << "[]" << endl;
        return;
    }

    queue<TreeNode *> q;
    q.push(root);
    vector<string> result;

    while (!q.empty())
    {
        TreeNode *node = q.front();
        q.pop();

        if (node)
        {
            result.push_back(to_string(node->val));
            q.push(node->left);
            q.push(node->right);
        } else
        {
            result.push_back("null");
        }
    }

    // 移除末尾的null
    while (!result.empty() && result.back() == "null")
    {
        result.pop_back();
    }

    cout << "[";
    for (int i = 0; i < result.size(); i++)
    {
        cout << result[i];
        if (i < result.size() - 1) cout << ",";
    }
    cout << "]" << endl;
}

// 辅助函数：中序遍历验证BST性质
void inorderTraversal(TreeNode *root, vector<int> &result)
{
    if (!root) return;
    inorderTraversal(root->left, result);
    result.push_back(root->val);
    inorderTraversal(root->right, result);
}

// 辅助函数：验证是否为有效的BST
bool isValidBST(TreeNode *root)
{
    vector<int> inorder;
    inorderTraversal(root, inorder);
    for (int i = 1; i < inorder.size(); i++)
    {
        if (inorder[i] <= inorder[i-1]) return false;
    }
    return true;
}

// 辅助函数：释放二叉树内存
void deleteTree(TreeNode *root)
{
    if (!root) return;
    deleteTree(root->left);
    deleteTree(root->right);
    delete root;
}

int main()
{
    Solution solution;

    cout << "=== LeetCode 701. 二叉搜索树中的插入操作 测试案例 ===" << endl << endl;

    // 测试案例1：题目示例1
    cout << "测试案例1：" << endl;
    vector<int> tree1 = {4, 2, 7, 1, 3};
    TreeNode *root1 = buildTreeFromArray(tree1);
    int val1 = 5;

    cout << "输入: root = ";
    printTree(root1);
    cout << "      val = " << val1 << endl;

    TreeNode *result1 = solution.insertIntoBST(root1, val1);
    cout << "输出: ";
    printTree(result1);
    cout << "验证BST性质: " << (isValidBST(result1) ? "通过" : "失败") << endl << endl;

    // 测试案例2：题目示例2
    cout << "测试案例2：" << endl;
    vector<int> tree2 = {40, 20, 60, 10, 30, 50, 70};
    TreeNode *root2 = buildTreeFromArray(tree2);
    int val2 = 25;

    cout << "输入: root = ";
    printTree(root2);
    cout << "      val = " << val2 << endl;

    TreeNode *result2 = solution.insertIntoBST(root2, val2);
    cout << "输出: ";
    printTree(result2);
    cout << "验证BST性质: " << (isValidBST(result2) ? "通过" : "失败") << endl << endl;

    // 测试案例3：题目示例3（空树）
    cout << "测试案例3（空树）：" << endl;
    TreeNode *root3 = nullptr;
    int val3 = 5;

    cout << "输入: root = ";
    printTree(root3);
    cout << "      val = " << val3 << endl;

    TreeNode *result3 = solution.insertIntoBST(root3, val3);
    cout << "输出: ";
    printTree(result3);
    cout << "验证BST性质: " << (isValidBST(result3) ? "通过" : "失败") << endl << endl;

    // 测试案例4：单节点树
    cout << "测试案例4（单节点树）：" << endl;
    vector<int> tree4 = {5};
    TreeNode *root4 = buildTreeFromArray(tree4);
    int val4 = 3;

    cout << "输入: root = ";
    printTree(root4);
    cout << "      val = " << val4 << endl;

    TreeNode *result4 = solution.insertIntoBST(root4, val4);
    cout << "输出: ";
    printTree(result4);
    cout << "验证BST性质: " << (isValidBST(result4) ? "通过" : "失败") << endl << endl;

    // 测试案例5：插入到右子树
    cout << "测试案例5（插入到右子树）：" << endl;
    vector<int> tree5 = {5, 3, 6, 2, 4};
    TreeNode *root5 = buildTreeFromArray(tree5);
    int val5 = 7;

    cout << "输入: root = ";
    printTree(root5);
    cout << "      val = " << val5 << endl;

    TreeNode *result5 = solution.insertIntoBST(root5, val5);
    cout << "输出: ";
    printTree(result5);
    cout << "验证BST性质: " << (isValidBST(result5) ? "通过" : "失败") << endl << endl;

    // 测试案例6：插入较小值
    cout << "测试案例6（插入较小值）：" << endl;
    vector<int> tree6 = {5, 3, 6, 2, 4};
    TreeNode *root6 = buildTreeFromArray(tree6);
    int val6 = 1;

    cout << "输入: root = ";
    printTree(root6);
    cout << "      val = " << val6 << endl;

    TreeNode *result6 = solution.insertIntoBST(root6, val6);
    cout << "输出: ";
    printTree(result6);
    cout << "验证BST性质: " << (isValidBST(result6) ? "通过" : "失败") << endl << endl;

    // 测试案例7：插入到深层位置
    cout << "测试案例7（插入到深层位置）：" << endl;
    vector<int> tree7 = {10, 5, 15, 3, 7, 12, 20, 1, 4, 6, 8};
    TreeNode *root7 = buildTreeFromArray(tree7);
    int val7 = 9;

    cout << "输入: root = ";
    printTree(root7);
    cout << "      val = " << val7 << endl;

    TreeNode *result7 = solution.insertIntoBST(root7, val7);
    cout << "输出: ";
    printTree(result7);
    cout << "验证BST性质: " << (isValidBST(result7) ? "通过" : "失败") << endl << endl;

    // 清理内存
    deleteTree(result1);
    deleteTree(result2);
    deleteTree(result3);
    deleteTree(result4);
    deleteTree(result5);
    deleteTree(result6);
    deleteTree(result7);

    cout << "所有测试案例执行完毕！" << endl;

    return 0;
}